package top.lingchen.blogapi.service.impl;

import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import top.lingchen.blogapi.bean.SysUser;
import top.lingchen.blogapi.service.TokenService;
import top.lingchen.blogapi.utils.JWTUtils;

import java.util.Map;

/**
 * @Author 凌宸
 * @create 2021-12-16 下午 6:40
 * @Description
 * @Version 1.0
 */
@Service
public class TokenServiceImpl implements TokenService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public SysUser checkToken(String token) {
        if(!StringUtils.hasLength(token)){ // token 为空
            return null;
        }
        Map<String, Object> stringObjectMap = JWTUtils.checkToken(token);
        if(stringObjectMap == null){ // 解析失败
            return null;
        }
        String userJson = stringRedisTemplate.opsForValue().get("TOKEN_" + token);
        if(!StringUtils.hasLength(userJson)){ // 过期
            return null;
        }
        SysUser sysUser = JSON.parseObject(userJson, SysUser.class);
        return sysUser;
    }

}
